package cn.yujiago.miaosha.rabbitmq;

import cn.yujiago.miaosha.dto.GoodsDTO;
import cn.yujiago.miaosha.entity.MiaoshaOrder;
import cn.yujiago.miaosha.redis.RedisService;
import cn.yujiago.miaosha.service.GoodsService;
import cn.yujiago.miaosha.service.MiaoshaService;
import cn.yujiago.miaosha.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MQReceiver {

    private static Logger log = LoggerFactory.getLogger(MQReceiver.class);

    @Autowired
    RedisService redisService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    OrderService orderService;
    @Autowired
    MiaoshaService miaoshaService;

    @RabbitListener(queues = MQConfig.MIAOSHA_QUEUE)
    public void receive(String message) {
        log.info("receive message:" + message);

        MiaoshaMessage mm  = RedisService.stringToBean(message, MiaoshaMessage.class);
        long userId = mm.getUserId();
        long goodsId = mm.getGoodsId();

        GoodsDTO goods = goodsService.getGoodsDTOById(goodsId);
        int stock = goods.getStockCount();
        if(stock <= 0) {
            return;
        }
        //判断是否已经秒杀到了，不能重复秒杀
        MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(userId, goodsId);
        if(order != null) {
            return;
        }
        //减库存 下订单 写入秒杀订单
        miaoshaService.miaosha(userId, goods);
    }

}
